package binarySearch;

/**
 * Created by hps on 17-5-1.
 */
public class OrdArray {
    private long[] a;
    private int nElems;

    public OrdArray(int max) {
        a = new long[max];
        nElems = 0;
    }

    public int size() {
        return nElems;
    }

    public int find(long searchKey) {
        return recFind(searchKey, 0, nElems - 1);
    }

    private int recFind(long searchKey, int lowerBound, int upperBound) {
        int curIn = (lowerBound + upperBound) / 2;
        if(a[curIn] == searchKey)
            return curIn;
        else if(lowerBound >= upperBound)
            return -1;
        else {
            if(a[curIn] > searchKey)
                return recFind(searchKey, lowerBound, curIn - 1);
            else
                return recFind(searchKey, curIn + 1, upperBound);
        }
    }

    public void insert(long value) {
        int j;
        for(j = nElems - 1; j >= 0 && a[j] > value; j--)
            a[j+1] = a[j];
        a[j + 1] = value;
        nElems++;
    }

    public void display() {
        for (int i = 0; i < nElems; i++) {
            System.out.print(a[i] + " ");
        }
        System.out.println();
    }
}
